<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
       
      <meta name="keywords" content="ES6、JS" />
       
      <meta name="description" content="ES6、JS" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>同构渲染react |  君书</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="君书" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-服务端渲染react"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  同构渲染react
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/28/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93react/" class="article-date">
  <time datetime="2022-02-28T07:42:16.000Z" itemprop="datePublished">2022-02-28</time>
</a>   
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="渲染"><a href="#渲染" class="headerlink" title="渲染"></a>渲染</h2><p>渲染即将数据和 html 进行拼接。渲染分为客户端渲染和服务端渲染，服务端渲染又可分为传统服务端渲染和同构渲染。</p>
<span id="more"></span>

<h3 id="客户端渲染（CSR）"><a href="#客户端渲染（CSR）" class="headerlink" title="客户端渲染（CSR）"></a>客户端渲染（CSR）</h3><p>客户端渲染即请求接口获取数据后，将数据与 html 进行拼装，完成页面渲染。具体的实现过程如下：</p>
<ol>
<li>输入网页地址回车后，客户端发送请求</li>
<li>服务端接收请求后，返回空白的 html 文档字符串</li>
<li>客户端接收到响应数据后，浏览器进行页面渲染，此时渲染后页面是空白的（因为没有具体 DOM）</li>
<li>客户端发送获取页面数据的请求</li>
<li>服务端查询数据库或通过读取文件的方式，返回数据</li>
<li>客户端拿到数据，将数据与 html 进行拼接，完成页面渲染</li>
</ol>
<p>通过上述 CSR 流程发现，客户端渲染需要请求接口后，才能获取页面内容再与 html 进行拼接，完成页面最终的渲染。即在获取数据前，页面是空白文档，这样是<code>不利于 SEO</code>的；同时由于客户端需要进行多次请求最终才能在页面上展示出内容，所以<code>对于首屏加载速度并不友好</code>。</p>
<p>针对以上两个问题，服务端渲染即可完美解决。</p>
<h3 id="服务端渲染（SSR）"><a href="#服务端渲染（SSR）" class="headerlink" title="服务端渲染（SSR）"></a>服务端渲染（SSR）</h3><p>服务端渲染即在服务端完成数据和 html 的拼接，将拼接后的内容返回给客户端。具体实现如下：</p>
<ol>
<li>输入网页地址回车后，客户端发送请求</li>
<li>服务端接收请求，进行数据和 html 的拼接，并将拼接后的内容返回</li>
<li>客户端接收到响应数据后，浏览器进行页面的渲染</li>
</ol>
<p>由于服务端渲染可直接将拼装后内容返回，当 SEO 进行抓取时，即可抓取到有效内容进行权重的分析，且服务端渲染不需要再通过请求获取数据，有效的减少了 http 的请求，缩短了首次加载时长。</p>
<p>在未使用框架开发前端组件时，我们一般采用的是传统的服务端渲染。但随着前端框架和生态圈的丰富和完善，传统的服务端渲染弊端也暴露无遗：</p>
<ol>
<li>前后端完全耦合，前端的发挥空间受到限制，同时后端的服务压力也剧增</li>
<li>无法实现 SPA （单页应用）</li>
<li>用户交互体验差</li>
<li>不利于协作开发</li>
<li>。。。</li>
</ol>
<p>为了实现前后端解耦，最大程度的发挥前端和后端优势，现代服务端的渲染即同构渲染应运而生。同构渲染的核心即：</p>
<ol>
<li>服务端渲染实现首屏直出（利于　SEO　和首屏加载）</li>
<li>客户端渲染接管用户交互（SPA，提高渲染性能）</li>
</ol>
<p>本次通过实现 react 的同构渲染学习具体实现方式，该项目代码存放在<a target="_blank" rel="noopener" href="https://gitee.com/xiaofujun/react-ssr">此处</a>。</p>
<h2 id="项目目录划分"><a href="#项目目录划分" class="headerlink" title="项目目录划分"></a>项目目录划分</h2><p>ssr 最重要的是同构（客户端和服务端尽可能的使用同一代码）。可将同构代码放置在一个文件夹下。</p>
<h2 id="服务端渲染之前的准备工作"><a href="#服务端渲染之前的准备工作" class="headerlink" title="服务端渲染之前的准备工作"></a>服务端渲染之前的准备工作</h2><h3 id="一-搭建服务端"><a href="#一-搭建服务端" class="headerlink" title="一. 搭建服务端"></a>一. 搭建服务端</h3><p>借用 express 框架快速搭建服务端应用。搭建完成后，校验服务端是否搭建成功。</p>
<p>搭建服务端应用具体代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> express <span class="keyword">from</span> <span class="string">&#x27;express&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app = express();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 将 public 文件夹设置为静态资源</span></span><br><span class="line">app.use(express.static(<span class="string">&#x27;public&#x27;</span>));</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">8080</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;服务启动在 8080 端口&#x27;</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> app;</span><br></pre></td></tr></table></figure>


<h3 id="二-配置-webpack-config-js"><a href="#二-配置-webpack-config-js" class="headerlink" title="二. 配置 webpack.config.js"></a>二. 配置 webpack.config.js</h3><h4 id="为什么要配置-webpack"><a href="#为什么要配置-webpack" class="headerlink" title="为什么要配置 webpack"></a>为什么要配置 webpack</h4><ol>
<li>使用 ESM 模块规范构建的服务端，但服务端模块标准使用的是 commonjs 规范，不能识别 esm，所以需要通过 webpack 进行编译打包后再运行。</li>
<li>node 环境和浏览器环境都无法直接识别 jsx 语法，需要使用 loader 编译。</li>
</ol>
<h4 id="重要的几项配置信息"><a href="#重要的几项配置信息" class="headerlink" title="重要的几项配置信息"></a>重要的几项配置信息</h4><ol>
<li>配置当前运行的目标环境。【<strong>target: node/web</strong>】</li>
<li>编译 jsx 语法的插件 <code>@babel/preset-react</code></li>
<li>添加 <code>core-js</code> 和 <code>regenerator-runtime</code> polyfill，在具体配置时，需要指明使用的 corejs 的版本号</li>
</ol>
<p>由于客户端和服务端的 webpack 配置信息有相同的部分，所以可抽离公共部分作为 <code>webpack.base.config.js</code>，下面将显示具体的配置信息：</p>
<p>公共 webpack 配置：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  mode: <span class="string">&#x27;development&#x27;</span>,</span><br><span class="line">  <span class="built_in">module</span>: &#123;</span><br><span class="line">    rules: [</span><br><span class="line">      &#123;</span><br><span class="line">        test: <span class="regexp">/\.js$/</span>,</span><br><span class="line">        loader: <span class="string">&#x27;babel-loader&#x27;</span>,</span><br><span class="line">        options: &#123;</span><br><span class="line">          presets: [</span><br><span class="line">            [</span><br><span class="line">              <span class="string">&#x27;@babel/preset-env&#x27;</span>, </span><br><span class="line">              &#123;</span><br><span class="line">                useBuiltIns: <span class="string">&#x27;usage&#x27;</span>,</span><br><span class="line">                corejs: <span class="string">&#x27;3&#x27;</span>,</span><br><span class="line">              &#125;</span><br><span class="line">            ], </span><br><span class="line">            <span class="string">&#x27;@babel/preset-react&#x27;</span></span><br><span class="line">          ]</span><br><span class="line">        &#125;,</span><br><span class="line">        exclude: <span class="regexp">/node_modules/</span>,</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>客户端 webpack 的配置如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> &#123; merge &#125; = <span class="built_in">require</span>(<span class="string">&#x27;webpack-merge&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> baseConfig = <span class="built_in">require</span>(<span class="string">&#x27;./webpack.base.config&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> clientConfig = &#123;</span><br><span class="line">  target: <span class="string">&#x27;web&#x27;</span>,  <span class="comment">// 运行在 node 环境中</span></span><br><span class="line">  entry: <span class="string">&#x27;./src/client/index.js&#x27;</span>,</span><br><span class="line">  output: &#123;</span><br><span class="line">    filename: <span class="string">&#x27;index.js&#x27;</span>,</span><br><span class="line">    path: path.join(__dirname, <span class="string">&#x27;public&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = merge(baseConfig, clientConfig);</span><br></pre></td></tr></table></figure>

<p>服务端 webpack 的配置如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> &#123; merge &#125; = <span class="built_in">require</span>(<span class="string">&#x27;webpack-merge&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> baseConfig = <span class="built_in">require</span>(<span class="string">&#x27;./webpack.base.config&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> serverConfig = &#123;</span><br><span class="line">  target: <span class="string">&#x27;node&#x27;</span>,  <span class="comment">// 运行在 node 环境中</span></span><br><span class="line">  entry: <span class="string">&#x27;./src/server/index.js&#x27;</span>,</span><br><span class="line">  output: &#123;</span><br><span class="line">    filename: <span class="string">&#x27;bundle.js&#x27;</span>,</span><br><span class="line">    path: path.join(__dirname, <span class="string">&#x27;build&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = merge(baseConfig, serverConfig);</span><br></pre></td></tr></table></figure>


<h3 id="三-配置-package-json-运行命令"><a href="#三-配置-package-json-运行命令" class="headerlink" title="三. 配置 package.json 运行命令"></a>三. 配置 package.json 运行命令</h3><p>搭建服务的源文件需要经过 webpack 编译后，才能在 node 中运行。为了简化开发中命令的执行，我们可借助插件 <code>npm-run-all</code>, 通过配置命令实现当源文件发生变化后自动构建编译，并在编译结束时，启动命令运行编译生成的文件。具体配置如下：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;server&quot;</span>: <span class="string">&quot;npm-run-all -p build:* -p server:*&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;server:source&quot;</span>: <span class="string">&quot;nodemon build/bundle.js&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;server:target&quot;</span>: <span class="string">&quot;webpack --config webpack.server.config.js --watch&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;server:public&quot;</span>: <span class="string">&quot;webpack --config webpack.client.config.js --watch&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;build:server&quot;</span>: <span class="string">&quot;webpack --config webpack.server.config.js&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;build:client&quot;</span>: <span class="string">&quot;webpack --config webpack.client.config.js&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过运行 <code>yarn server</code> 即可开启服务。当开发过程中文件发生变动，会根据配置的命令自动加载最新的资源。</p>
<p>上述准备工作做好后，下面开始 react 服务端渲染相关的开发。</p>
<h2 id="服务端渲染（ssr）"><a href="#服务端渲染（ssr）" class="headerlink" title="服务端渲染（ssr）"></a>服务端渲染（ssr）</h2><p>客户端发出请求后，服务端会返回 html 字符串作为响应。若使用 React 进行 ssr，则需要将组件通过 <code>renderToString()</code> 转为 html 字符串才能返回给客户端。</p>
<h3 id="一-ssr-脱水"><a href="#一-ssr-脱水" class="headerlink" title="一. ssr 脱水"></a>一. ssr 脱水</h3><p>ssr 只会返回 html 结构，迅速响应客户端请求，组件挂载过程中生命周期函数和元素上的事件属性会被过滤。所以若想为组件添加事件，需要在客户端通过 <code>hydrate()</code> 进行组件的二次渲染。具体步骤如下：</p>
<ol>
<li>组件上添加事件属性</li>
<li>客户端使用 <code>React.hydrate(Component, root)</code> 对已有的 Component 进行二次渲染【元素事件等属性的添加以及其生命周期函数的执行】</li>
<li>将客户端的代码通过 webpack 打包到 public 文件夹下</li>
<li>在服务端将 public 文件夹设置为静态资源</li>
<li>服务端返回的 html 字符串中通过 script 引入客户端打包后的 js 文件</li>
</ol>
<h3 id="二-路由"><a href="#二-路由" class="headerlink" title="二. 路由"></a>二. 路由</h3><p>路由分为客户端和服务端。当浏览器禁用 javascript 时，服务端路由存在可保证页面访问正常。客户端使用 History 路由模式实现单页应用，服务端使用 StaticRouter 实现静态路由。具体实现过程如下：</p>
<ol>
<li>服务端和客户端公用一套路由信息</li>
<li>服务端路由跳转采用的是 a 标签，客户端路由跳转采用的是 js 实现单页应用。</li>
</ol>
<p>客户端和服务端添加路由代码具体如下：</p>
<p>同构路由信息</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Home <span class="keyword">from</span> <span class="string">&#x27;./component/Home&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> listRoute <span class="keyword">from</span> <span class="string">&#x27;./component/List&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> [</span><br><span class="line">  &#123;</span><br><span class="line">    path: <span class="string">&#x27;/&#x27;</span>,</span><br><span class="line">    component: Home,</span><br><span class="line">    exact: <span class="literal">true</span></span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    path: <span class="string">&#x27;/list&#x27;</span>,</span><br><span class="line">    ...listRoute,</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>客户端路由</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> routes <span class="keyword">from</span> <span class="string">&#x27;../share/route&#x27;</span>;</span><br><span class="line">ReactDOM.hydrate(&lt;BrowserRouter&gt;</span><br><span class="line">  &#123;</span><br><span class="line">    routes.map(<span class="function"><span class="params">routeProps</span> =&gt;</span> (</span><br><span class="line">      &lt;Route key=&#123;routeProps.path&#125; &#123;...routeProps&#125; /&gt;</span><br><span class="line">    ))</span><br><span class="line">  &#125;</span><br><span class="line">&lt;/BrowserRouter&gt;, <span class="built_in">document</span>.getElementById(<span class="string">&#x27;root&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p>服务端路由</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> routes <span class="keyword">from</span> <span class="string">&#x27;../share/route&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> content = renderToString(</span><br><span class="line">  &lt;StaticRouter location=&#123;req.path&#125;&gt;</span><br><span class="line">    &#123; routes.map(<span class="function"><span class="params">item</span> =&gt;</span> <span class="xml"><span class="tag">&lt;<span class="name">Route</span> <span class="attr">key</span>=<span class="string">&#123;item.path&#125;</span> &#123;<span class="attr">...item</span>&#125; /&gt;</span></span>) &#125;</span><br><span class="line">  &lt;/StaticRouter&gt;</span><br><span class="line">);</span><br></pre></td></tr></table></figure>


<h3 id="三-Redux-状态管理"><a href="#三-Redux-状态管理" class="headerlink" title="三. Redux 状态管理"></a>三. Redux 状态管理</h3><p>Action 和 Reducer 属于同构部分，store 客户端创建方式和服务端有些许不同，服务端在接收到请求后才会创建 store。由于服务端渲染组件时，组件挂载过程中生命周期内的 js 代码不会执行，所以导致服务端渲染时获取到的 store 为空，解决这个问题的具体步骤如下：</p>
<ol>
<li>组件添加 getData 方法，用于获取渲染需要的数据</li>
<li>将 getData 方法放到路由信息中</li>
<li>服务端接收到客户端的请求，通过路由匹配到当前的路由信息，执行路由信息中的 getData 方法，为 store 添加数据</li>
</ol>
<p>由于代码繁琐，不再赘述具体的实现过程。若想查看源码，可到<a target="_blank" rel="noopener" href="https://gitee.com/xiaofujun/react-ssr">此处</a>。</p>
<h2 id="服务端渲染-OR-客户端渲染"><a href="#服务端渲染-OR-客户端渲染" class="headerlink" title="服务端渲染 OR 客户端渲染"></a>服务端渲染 OR 客户端渲染</h2><p>服务端渲染即将 html 和数据在后台进行组装，将组装后 html 再返回给客户端。客户端接收到资源后，交给render进程。render 进程中的 GUI 线程负责解析HTML文档构建DOM树，解析CSS文件构建CSSOM，合并构成渲染树。除此之外，浏览器中其他进程和线程会解析执行 js 脚本和下载其他资源。最终通过 GPU 进程将图层合成展示到页面上。</p>
<p>服务端渲染的优点：</p>
<ol>
<li>利于 SEO</li>
<li>解决首屏加载时间过长</li>
</ol>
<p>但其缺点也是显而易见的。相同的功能需要在客户端和服务端都实现，这会导致项目中代码量增加以及增加维护同构代码的工作量。所以对于 SEO 要求不高的项目，需要谨慎选用 SEO。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://xiaofujun.gitee.io/2022/02/28/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B8%B2%E6%9F%93react/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/ssr/" rel="tag">ssr</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/02/28/http%E7%BC%93%E5%AD%98/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            http缓存
          
        </div>
      </a>
    
    
      <a href="/2022/02/24/React%E5%87%BD%E6%95%B0%E7%BB%84%E4%BB%B6%E7%9A%84hook/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">React函数组件的hook</div>
      </a>
    
  </nav>

  
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> 小付君
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="君书"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>